package top.gytf.unifiedcall.support.web.mvc.producer;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.gytf.unifiedcall.common.api.ApiDefinition;
import top.gytf.unifiedcall.common.api.ApiDefinitionFactory;
import top.gytf.unifiedcall.producer.response.ResponseHandlerContext;
import top.gytf.unifiedcall.producer.response.ResponseHandlerManager;
import top.gytf.unifiedcall.producer.response.SimpleResponseHandlerContext;

import java.lang.reflect.Method;

/**
 * WebMVC下对于响应处理的适配器
 */
@Slf4j
@RestControllerAdvice
@RequiredArgsConstructor
public class UnifiedCallResponseHandleAdapter implements ResponseBodyAdvice<Object> {
    private final ApiDefinitionFactory apiDefinitionFactory;
    private final ResponseHandlerManager responseHandlerManager;
    private final ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (ResponseHandlerContext.class.isAssignableFrom(returnType.getParameterType())) {
            // 允许ResponseHandlerContext
            return true;
        }

        Method method = returnType.getMethod();
        if (method == null) {
            return false;
        }
        ApiDefinition apiDefinition = apiDefinitionFactory.create(method);
        return responseHandlerManager.isSupported(apiDefinition);
    }

    @Nullable
    @Override
	@SneakyThrows
    public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ResponseHandlerContext context;
        if (body instanceof ResponseHandlerContext rhc) {
            context = rhc;
        } else {
            Method method = returnType.getMethod();
            Assert.notNull(method, "请求处理的API Method为空");
            context = createContext(method, body);
        }

        Object result = responseHandlerManager.handle(context);
        // String类型不返回String会报错
		if (body instanceof String && !(result instanceof String)) {
			return objectMapper.writeValueAsString(result);
		}

        return result;
    }

    @Nullable
    @ResponseBody
    @ExceptionHandler(Throwable.class)
    public Object resolveException(Throwable throwable, HandlerMethod handlerMethod) throws Throwable {
        ResponseHandlerContext context = createContext(handlerMethod.getMethod(), throwable);
        if (!responseHandlerManager.isSupported(context.getApiDefinition())) {
            // 不支持处理
            throw throwable;
        }
        return context;
    }

    protected ResponseHandlerContext createContext(Method apiMethod, @Nullable Object response) {
        ApiDefinition apiDefinition = apiDefinitionFactory.create(apiMethod);
        return SimpleResponseHandlerContext.builder()
                .apiDefinition(apiDefinition)
                .response(response)
                .build();
    }
}
